package mirkofrancuski.battleship.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class HighScoreTable {
	private static String DEBUG_TAG = "DEBUG HighScoreTable";
	

	private static final String HIGHSCORE_TABLE = "Highscore_Table";
	private static final String HIGHSCORE_ID = "Highscore_ID";
	private static final String HIGHSCORE_PLAYER_NAME = "Player_Name";
	private static final String HIGHSCORE_ADVERSARY_NAME = "Adversary_Name";
	private static final String HIGHSCORE_NUMBER_OF_MOVES = "Number_Of_Moves";

	private static final String CREATE_HIGH_SCORE_TABLE = 
			"CREATE TABLE "	+ HIGHSCORE_TABLE 
			+ " (" 
			+ HIGHSCORE_ID + " INTEGER PRIMARY KEY, "
			+ HIGHSCORE_PLAYER_NAME + " TEXT, " 
			+ HIGHSCORE_ADVERSARY_NAME + " TEXT, " 
			+ HIGHSCORE_NUMBER_OF_MOVES + " INTEGER" 
			+ ")";

	public static void onCreate(SQLiteDatabase database) {
		database.execSQL(CREATE_HIGH_SCORE_TABLE);
	}

	public static void onUpgrade(SQLiteDatabase database, int oldVersion,
			int newVersion) {
		Log.w(HighScoreTable.class.getName(),
				"Upgrading database from version " + oldVersion + " to "
						+ newVersion + ", which will destroy all old data");
		database.execSQL("DROP TABLE IF EXISTS " + HIGHSCORE_TABLE);
		onCreate(database);
	}

	public static boolean addHighScore(SQLiteDatabase db,
			HighScoreInfo highScoreInfo) {
		List<HighScoreInfo> allHighScores = getAllHighScores(db);

		// check if highScore can be inserted in the table
		if (allHighScores.size() == 10) {
			if (allHighScores.get(9).getNumberOfMoves() < highScoreInfo.getNumberOfMoves()) {				
				return false;
			}

			// if new high score is higher that the lowest one than it should be
			// inserted and last one will be deleted
			else {
				deleteHighScore(db, allHighScores.get(9).getId());				
			}
		}

		ContentValues cv = new ContentValues();
		cv.put(HIGHSCORE_ID, highScoreInfo.getId());
		cv.put(HIGHSCORE_PLAYER_NAME, highScoreInfo.getPlayerName());
		cv.put(HIGHSCORE_ADVERSARY_NAME, highScoreInfo.getAdversaryName());
		cv.put(HIGHSCORE_NUMBER_OF_MOVES, highScoreInfo.getNumberOfMoves());

		db.insert(HIGHSCORE_TABLE, null, cv);
		return true;
	}

	public static List<HighScoreInfo> getAllHighScores(SQLiteDatabase db) {
		List<HighScoreInfo> allHighscores = new ArrayList<HighScoreInfo>();
		String selectQuery = "SELECT * FROM " + HIGHSCORE_TABLE + " ORDER BY "
				+ HIGHSCORE_NUMBER_OF_MOVES + " ASC";
		Cursor cursor = null;
		
		try {
		
		cursor = db.rawQuery(selectQuery, null);
		
		for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
			HighScoreInfo highScoreInfo = null;

			highScoreInfo = new HighScoreInfo(
					Integer.parseInt(cursor.getString(0)), // id
					cursor.getPosition()+1, // Rank
					cursor.getString(1), // Player name
					cursor.getString(2), // Adversary name
					Integer.parseInt(cursor.getString(3))); // Number of moves

			allHighscores.add(highScoreInfo);			
		}
		
		
		} finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }		
		}
		
		return allHighscores;
	}

	public static void deleteHighScore(SQLiteDatabase db, int id) {
		Log.d(DEBUG_TAG, "HighScores: \n" + getAllHighScores(db));
	 
		db.delete(HIGHSCORE_TABLE, HIGHSCORE_ID + " = ?", new String[] { String.valueOf(id) });
			
		Log.d(DEBUG_TAG, "HighScores -1: \n" + getAllHighScores(db));
	}

	public static int updateHighScore(SQLiteDatabase db, HighScoreInfo highScore) {
		ContentValues cv = new ContentValues();
		cv.put(HIGHSCORE_ID, highScore.getId());
		cv.put(HIGHSCORE_PLAYER_NAME, highScore.getPlayerName());
		cv.put(HIGHSCORE_ADVERSARY_NAME, highScore.getAdversaryName());
		cv.put(HIGHSCORE_NUMBER_OF_MOVES, highScore.getNumberOfMoves());

		return db.update(HIGHSCORE_TABLE, cv, HIGHSCORE_ID + " = ?", new String[] { String.valueOf(highScore.hashCode()) });
	}

}
